package com.itheima.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.controller.Response.R;
import com.itheima.untils.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter(filterName = "loginCheck",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();
        log.info("请求的路径为:{}",requestURI);
        String[] url={
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/login",
                "/user/logout",
                "/user/sendMsg"
        };
        boolean check = check(url, requestURI);
        if (check){
            chain.doFilter(request,response);
            return;
        }
        if (request.getSession().getAttribute("employee")!=null){
            Long employee = (Long) request.getSession().getAttribute("employee");
            BaseContext.setEmployeeId(employee);
            chain.doFilter(request,response);
            return;
        }
        if (request.getSession().getAttribute("user")!=null){
            Long user = (Long) request.getSession().getAttribute("user");
            BaseContext.setEmployeeId(user);
            chain.doFilter(request,response);
            return;
        }

        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;


    }

/**
*@Author: wang
  *@Desc:匹配路径是否相同，如果相同则放行。
 * @Date: 2022/8/15 19:44
 */
    public boolean check(String[] paths,String url){
        for (String path : paths) {
            boolean match = PATH_MATCHER.match(path, url);
            if (match){
                return true;
            }
        }
        return false;
    }
}
